var validator=require('validator')
var TopicModel=require('../models/topic')
var ReplyModel=require('../models/reply')
var eventproxy=require('eventproxy')
var common=require('../common/function.js')
var _ = require('lodash')
exports.showTopicCreate=(req,res)=>{
	res.render('topic/create')
}
exports.topicCreate=(req,res)=>{
	var title=validator.trim(req.body.title)
	var tab=validator.trim(req.body.tab)
	var content=validator.trim(req.body.t_content)
	var hasEmptyInfo=[title,tab,content].some((item)=>{
		return item===''
	})
	if(hasEmptyInfo){
		res.status(422)
		return res.render('topic/create',{error:'您填写的信息不完整'})
	}
	var topicData={
		title:title,
		content:content,
		tab:tab,
		username:global.current_user.username,
		insertTime:Date.now()
	}
	TopicModel.addTopic(topicData,(err,response)=>{
		return res.render('topic/create',{success:'发表话题成功'})
	})
}
exports.detail=(req,res)=>{
	//body post param get
	var topicId=req.params.tid
	var ep=new eventproxy()
	TopicModel.getTopic(topicId,(err,topic)=>{
		topic.timeStr=common.formatTime(topic.insertTime)
		ep.emit('topic_data_ok',topic)
	})
	ReplyModel.count({topicId:topicId},(err,count)=>{
		ep.emit('reply_count_ok',count)
	})
	ReplyModel.getReplys(topicId,(err,replys)=>{
		replys=_.map(replys,(reply)=>{
			reply.timeStr=common.formatTime(reply.insertTime)
			return reply
		})
		ep.emit('replys_data_ok',replys)
	})
	ep.all('topic_data_ok','reply_count_ok','replys_data_ok',(topic,count,replys)=>{
		res.render('topic/detail',{topic:topic,count:count,replys:replys})
	})
}